/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */


#include "threadptr.h"
#include "thread.h"

namespace Wishmaster
{
	ThreadPtr::ThreadPtr() : m_refcount(0), m_thread(0)
	{
	}

	ThreadPtr::ThreadPtr(Thread* t)
	{
		if(t)
		{
			m_refcount = new QAtomicInt();
			m_refcount->ref();
		}
		m_thread = t;
	}

	ThreadPtr::ThreadPtr(const ThreadPtr& t)
	{
		if(t.m_thread)
		{
			if(t.m_refcount->ref())
			{
				m_refcount = t.m_refcount;
				m_thread = t.m_thread;
			}
		}
		else
		{
			m_refcount = 0;
			m_thread = 0;
		}
	}

	ThreadPtr::~ThreadPtr()
	{
		if(m_thread && !m_refcount->deref())
		{
			delete m_thread;
			delete m_refcount;
		}
	}

	ThreadPtr& ThreadPtr::operator=(Thread* t)
	{
		if(t == m_thread)
			return *this;
		
		if(m_thread)
			log(llDebug, "[4]t:%p, ref--: %d", m_thread, (int)*m_refcount);
		if(m_thread && !m_refcount->deref())
		{
			delete m_thread;
			delete m_refcount;
		}

		m_thread = t;
		m_refcount = new QAtomicInt();
		m_refcount->ref();
		if(t == NULL)
			log(llDebug, "NULL alpha condition in ThreadPtr");
		return *this;
	}

	ThreadPtr& ThreadPtr::operator=(const ThreadPtr& t)
	{
		if(t.m_thread == m_thread)
			return *this;

		if(m_thread && !m_refcount->deref())
		{
			delete m_thread;
			delete m_refcount;
		}

		m_thread = t.m_thread;
		m_refcount = t.m_refcount;
		if(m_refcount)
			m_refcount->ref();
		return *this;
	}

	Thread* ThreadPtr::operator->()
	{
		return m_thread;
	}
	const Thread* ThreadPtr::operator->() const
	{
		return m_thread;
	}

	bool ThreadPtr::operator!() const
	{
		return (m_thread == 0);
	}

	bool ThreadPtr::operator==(const ThreadPtr& t) const
	{
		return (m_thread == t.m_thread);
	}

	bool ThreadPtr::isNull() const
	{
		return (m_thread == 0);
	}

	int ThreadPtr::refCount() const
	{
		return *m_refcount;
	}
	bool ThreadPtr::sortFunction(const ThreadPtr t1, const ThreadPtr t2)
	{
		return t1->threadTimestamp() > t2->threadTimestamp();
	}
}

